<!-- 客户订单页面 -->
<template>
    <div>
        <!-- 搜查组 -->
        <el-card v-if="showSearch" style="margin-bottom:20px ;">
            <el-form :model="searchForm">
                <el-row :gutter="24">
                    <el-col :span="6">
                        <el-form-item label="订单编码" :class="{ 'bold-label': true }">
                            <el-input v-model="searchForm.clientOrderCode" placeholder="请输入订单编码" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="客户名称" :class="{ 'bold-label': true }">
                            <el-input v-model="searchForm.clientName" placeholder="请输入客户名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="订货日期" :class="{ 'bold-label': true }">
                            <el-date-picker v-model="orderDateRange" type="daterange" range-separator="-"
                                value-format="YYYY-MM-DD" @change="handleDateChange" start-placeholder="开始日期"
                                end-placeholder="结束日期" style="width: 200px;" :defaultTime="defaultTime" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="交货日期" :class="{ 'bold-label': true }">
                            <el-date-picker v-model="deliveryDateRange" type="daterange" range-separator="-"
                                value-format="YYYY-MM-DD" @change="handleDateChangeT" start-placeholder="开始日期"
                                end-placeholder="结束日期" style="width: 200px;" :defaultTime="defaultTime" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item>
                            <el-button :icon="Search" type="primary" @click="onSearch">搜索</el-button>
                            <el-button :icon="Refresh" plain @click="onReset">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <el-card>
            <!-- 按钮组 -->
            <el-row class="button-group">
                <el-col :span="10">
                    <div>
                        <el-button type="primary" :icon="Plus" plain @click=onAdd>新增</el-button>
                        <el-button type="success" plain :disabled="isSingleRowSelected" :icon="EditPen"
                            @click="onModify">修改</el-button>
                        <el-button type="danger" plain :disabled="deleteDisabled" :icon="Delete"
                            @click="onDelete">删除</el-button>
                        <el-button type="warning" plain :icon="Download" @click="onExport">导出</el-button>
                    </div>
                </el-col>
                <el-col :span="14">
                    <div class="button-right">
                        <el-tooltip content="隐藏搜索" placement="top">
                            <el-button :icon="Search" circle @click="toggleSearch" />
                        </el-tooltip>
                        <el-tooltip content="刷新" placement="top">
                            <el-button :icon="Refresh" circle @click="refresh" />
                        </el-tooltip>
                    </div>
                </el-col>
            </el-row>
            <!-- 表格组件 -->
            <el-table :data="tableData" style="width: 100%" max-height="400px"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="40" :selectable="canSelectRow" />
                <el-table-column label="订单编码" width="130px" align="center" show-overflow-tooltip>
                    <template #default="{ row }">
                        <span style="color: #1890ff;" @click="showOrderDetails(row)">{{
                            row.clientOrderCode }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="clientName" label="客户名称" align="center" show-overflow-tooltip />
                <el-table-column prop="orderDate" width="130px" label="订货日期" align="center" />
                <el-table-column prop="deliveryDate" width="130px" label="交货日期" align="center" />
                <el-table-column prop="spec" width="100px" label="规格型号" align="center" />
                <el-table-column prop="orderQuantity" width="130px" label="订货数量" align="center" show-overflow-tooltip />
                <el-table-column prop="unitOfMeasure" label="单位" />
                <el-table-column prop="status" width="130px" label="订单状态" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === 'WORK_ORDER_FINISHED' ? 'success' : 'info'">
                            {{ scope.row.status === 'WORK_ORDER_FINISHED' ? '已生成生产订单' : '草稿' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="qualityRequirement" label="质量要求" show-overflow-tooltip />
                <el-table-column label="操作" width="220px" align="center">
                    <template #default="scope">
                        <!-- 只有当订单状态为 "草稿" 时，才显示 "修改" 和 "删除" 按钮 -->
                        <template v-if="scope.row.status === 'PREPARE'">
                            <el-button type="primary" plain text size="small" :icon="EditPen"
                                @click="handleEdit(scope.row)">修改</el-button>
                            <el-button type="primary" plain text size="small" :icon="Delete"
                                @click="handleDelete(scope.row)">删除</el-button>
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <div class="pagination">
                <el-pagination :current-page="searchForm.currentPage" :page-size="searchForm.pageSize"
                    :page-sizes="pageSizes" :total="pageResult.total" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 客户订单详情 -->
        <OrderFind :orderDialog="shadowTabs" :materialList="materialList" :AddValue="AddValue"
            @close-dialog="colseDialog" />

        <!-- 添加弹窗显示 -->
        <AddDialog :addDialog="dialogVisibleAdd" :units="units" @close-dialog="colseDialog" />

        <!-- 修改弹窗显示 :destroy-on-close="true"-->
        <UpdateDialog :key="UpdateValue.productCode" :updateDialog="dialogVisibleUpdate" :units="units"
            :UpdateValue="UpdateValue" @close-dialog="colseDialog" />

    </div>
</template>

<script setup>
import AddDialog from '@/components/CustomerOrders/AddDialog.vue';
import UpdateDialog from '@/components/CustomerOrders/UpdateDialog.vue';
import OrderFind from '@/components/CustomerOrders/OrderFind.vue';
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Delete, Download, Plus, EditPen } from '@element-plus/icons-vue';
import { findTableAssociation, findMaterial, deleteCustomerOrders } from '@/apis/lth/index';
import { getPageUnits } from '@/apis/zyj/units';
let now = new Date();
let startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);//开始时间默认为 00:00:00
let endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);//结束时间默认为 23:59:59
let defaultTime = ref([startOfDay, endOfDay]);//默认日期时间
const dialogVisibleAdd = ref(false);//添加客户订单弹窗
const dialogVisibleUpdate = ref(false);//修改客户订单弹窗
const shadowTabs = ref(false);//物料详情弹窗
const searchForm = reactive({
    currentPage: 1,
    pageSize: 10,
    clientOrderCode: '',
    clientName: '',
    startOrderDate: '',//订货日期
    endOrderDate: "",
    startDeliveryDate: "",//交货日期
    endDeliveryDate: "",
})
const orderDateRange = ref('')
const deliveryDateRange = ref('')
let ids = ref([]); // 选中行的id数组
let roleVal = ref([]); //选中行完整数据
const deleteDisabled = ref(true); // 删除按钮禁用状态,默认禁用
const isSingleRowSelected = ref(true); // 修改按钮禁用状态,默认禁用
const tableData = ref([]); //表格数据
const pageResult = ref({}); // 分页数据
let materialList = ref([]);//物料需求列表
const UpdateValue = ref({});//存储修改时选中行数据
const units = ref([]);//单位数据 
onMounted(async () => {
    units.value = await getPageUnits('', '', '-1', '-1');//挂载单位数据
})

const loadList = async () => {//加载客户订单数据
    await findTableAssociation(searchForm).then(res => {
        pageResult.value = res;
        tableData.value = pageResult.value.records
    });
}

// 分页大小
const pageSizes = [10, 20, 30, 40, 50]
/**
 * 处理分页大小变化
 * @param size 当前分页大小
 */
const handleSizeChange = async (size) => {
    searchForm.pageSize = size;
    loadList();
}
/**
 * 处理当前页码变化
 * @param currentPage 当前页码
 */
const handleCurrentChange = async (currentPage) => {
    searchForm.currentPage = currentPage
    loadList();
}
//搜索功能
const onSearch = async () => {
    console.log(searchForm)
    loadList();
}
//搜索条件重置
const onReset = async () => {
    Object.keys(searchForm).forEach(key => {
        searchForm[key] = null
    })
    orderDateRange.value = ''
    deliveryDateRange.value = ''
    loadList();
}
//隐藏搜索条件
const showSearch = ref(true);
const toggleSearch = () => {
    showSearch.value = !showSearch.value;
}
//刷新(图标)
const refresh = () => {
    loadList();
}

//新增客户订单
const onAdd = () => {
    dialogVisibleAdd.value = true;
}
//修改客户订单
const onModify = () => {
    dialogVisibleUpdate.value = true;
}
const canSelectRow = (row) => {// 如果状态不是 PREPARE，则返回 false
    return row.status === "PREPARE";
}
//删除客户订单
const onDelete = () => {
    ElMessageBox.confirm('确定要删除选中的订单吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        await deleteCustomerOrders(ids.value).then((res) => {
            if (res === "成功") {
                ElMessage.success(`删除成功`);
                loadList();
            } else {
                ElMessage.success(`删除失败`);
            }
        });
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}
//导出
const onExport = () => {
    ElMessage.success('导出功能已触发')
}
// handleDateChange：通常用于处理日期选择器（如 el-date-picker）的值变化事件。
const handleDateChange = (value) => {//订货日期
    if (value) {
        searchForm.startOrderDate = value[0];
        searchForm.endOrderDate = value[1];
    } else {
        searchForm.startOrderDate = null;
        searchForm.endOrderDate = null;
    }
}
const handleDateChangeT = (value) => {//交货日期
    if (value) {
        searchForm.startDeliveryDate = value[0];
        searchForm.endDeliveryDate = value[1];
    } else {
        searchForm.startDeliveryDate = null;
        searchForm.endDeliveryDate = null;
    }
}

// 处理选中行变化,val 选中行的数组
const handleSelectionChange = (val) => {
    console.log(val)
    deleteDisabled.value = !val.length
    ids.value = val.map(item => item.clientOrderId) // 使用map方法过滤出选中行的roleId数组
    roleVal.value = val.map(item => item); // 存储选中行的完整数据
    isSingleRowSelected.value = !(val.length === 1); // 如果只有一个选中行，则启用修改按钮
    if (!isSingleRowSelected.value) {
        UpdateValue.value = { ...val[0] };//把选中的这条数据添加给修改数据
    }
}
const AddValue = reactive({
    productId: '',//产品编号
    productCode: '',//产品编码
    productName: '',//产品名称
    productSpec: '',//产品规格
    clientOrderCode: '',//订单编码
    clientId: '',//客户编号
    clientCode: '',//客户编码
    clientName: '',//客户名称
    orderDate: '',//订货日期
    deliveryDate: '',//交货日期
    orderQuantity: 1,//订货数量
    unitOfMeasure: '',//单位
    spec: '',//规格型号
    qualityRequirement: '',//质量要求
});
//查询客户订单详情
const showOrderDetails = (row) => {
    Object.assign(AddValue, row)
    shadowTabs.value = true;
    findMaterial(row.clientOrderCode).then(res => {
        materialList.value = res;
    });
}
//修改订单
const handleEdit = (row) => {
    Object.assign(UpdateValue.value, row);
    dialogVisibleUpdate.value = true;
}
//删除订单
const handleDelete = (row) => {
    ids.value.length = 0;
    ids.value.push(row.clientOrderId);
    ElMessageBox.confirm(`是否确认要删除订单编码为"${row.clientOrderCode}"吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        await deleteCustomerOrders(ids.value).then((res) => {
            if (res === "成功") {
                ElMessage.success(`删除成功`);
                loadList();
            } else {
                ElMessage.success(`删除失败`);
            }
        });
    }).catch(() => {
        // ElMessage.info('已取消删除')
    })
}
//关闭弹窗事件
const colseDialog = async () => {
    dialogVisibleAdd.value = false;
    dialogVisibleUpdate.value = false;
    shadowTabs.value = false;
    await loadList();
}
//挂载查询数据
onMounted(() => {
    loadList();
})
</script>

<style scoped>
/* 使用 ::v-deep 选择器 */
::v-deep .el-table .el-table__header-wrapper thead tr th {
    background-color: #f8f8f9 !important;
    /* 你可以根据需要更改颜色 */
    color: #515a6e !important;
    /* 文字颜色 */
}

/* 如果需要更具体的控制，可以使用更详细的类名 */
::v-deep .el-table .el-table__header-wrapper thead tr th,
::v-deep .el-table .el-table__body-wrapper tbody tr td {
    padding-left: 0 !important;
    /* 移除左边距 */
}

/* 使用 ::v-deep 选择器来穿透作用域样式 */
::v-deep.el-table th,
::v-deep .el-table td {
    padding-left: 0 !important;
    /* 移除左边距 */
}

::v-deep .bold-label .el-form-item__label {
    font-weight: bold !important;
}

.table-operations {
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}

.el-pagination {
    justify-content: flex-end;
}

.button-right {
    text-align: right;
}

.button-group {
    margin-top: 20px;
    margin-bottom: 10px;
}
</style>